// 正则表达式
const phoneRegex = /^1[3-9]\d{9}$/;
// const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,12}$/;
const passwordRegex = /^.{8,16}$/;
const smsRegex = /^[A-Za-z\d!@#$%^&*]{6,}$/;
const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

// 验证函数
function validatePhone(phone) {
    return phoneRegex.test(phone);
}

// 验证函数
function validateEmail(phone) {
    return emailRegex.test(phone);
}

//验证密码
function validatePassword(password) {
    return passwordRegex.test(password);
}

//852fx5xx3061.vicp.fun
function validateSMS(sms) {
    return smsRegex.test(sms);
}

// 显示错误消息
function showError(message) {
    document.getElementById("errorMsg").innerText = message;
    document.getElementById("errorDialog").style.display = "block";
}

// 关闭错误提示
function closeError() {
    document.getElementById("errorDialog").style.display = "none";
}

// 初始化页面内容
function initContent() {
    //模版
    const defaultContent =
        `
        <label for="usr" class="form-label">账号:</label>
        <input type="text" name="username" placeholder="请输入用户名" id="username" class="form-control" style="width: 300px;margin: 5px 0;">
        <label for="paw" class="form-label">密码:</label>
        <input type="password" name="password" placeholder="请输入密码" id="password" class="form-control" style="width: 300px;margin: 5px 0;">
        <div style="margin-top: 15px;">
            <a href="/update/pwd_page">忘记密码？</a>
            <a href="/register_page" style="float:right;">注册</a>
        </div>
        <div style="text-align: center;margin-top: 25px;font-size: 11px;">
            <label for="is_check"></label><input type="checkbox" id="is_check"><span>我已阅读并同意 <a href="http://baidu.com">《用户服务协议》</a>和<a href="http://baidu.com">《隐私政策》</a></span>
        </div>
        <button class="btn btn-outline-light" style="margin-top: 10px;width: 100px;float:right;" id="login_usrLogin">登录</button>
    `;

    //模版
    const mobileContent =
        `
        <label for="mobile" class="form-label" style="margin-top: 20px;color: #005cbf">手机号:</label>
        <input type="text" name="mobile" placeholder="请输入手机号或邮箱" id="mobile" class="form-control" style="width: 300px;margin: 5px 0;">
        <label for="sms" class="form-label" style="margin-top: 15px;color: #005cbf;display: block">验证码:</label>
        <input type="text" name="sms" placeholder="请输入验证码" id="sms" class="form-control" style="width: 200px;margin: 5px 0; display:inline-block">
        <button style="width: 95px;margin-bottom: 5px;" id="sendSms" class="btn btn-group-toggle">验证码</button>
        <div style="margin-top: 6px;">
            <a href="/register_page" style="float:right;">注册</a>
        </div>
        <div style="text-align: center;font-size: 11px;clear:both; margin-top: 55px;">
            <input type="checkbox" id='is_check'><span>我已阅读并同意 <a href="http://baidu.com">《用户服务协议》</a>和<a href="http://baidu.com">《隐私政策》</a></span>
        </div>
        <button class="btn btn-outline-light" style="margin-top: 10px;width: 100px;float:right;" id="login_mobileLogin">登录</button>
    `;

    //改变内容
    function updateContent(content) {
        $("#content").html(content);
        bindEvents();
    }

    //绑定事件
    function bindEvents() {
        $("#userLogin").click(() => updateContent(defaultContent));
        $("#mobileLogin").click(() => updateContent(mobileContent));

        $("#login_usrLogin").click(handleUserLogin);
        $("#sendSms").click(handleSendSms);
        $("#login_mobileLogin").click(handleMobileLogin);
        $("#up_pwd").click(updatePwd);
    }
    //账户密码登录
    function handleUserLogin() {
        const username = $("#username").val();
        const password = $("#password").val();
        const agreement = document.getElementById("is_check");

        if (!username || !password) {
            showError("用户名或密码不能为空");
            return;
        }

        if (!validatePassword(password)) {
            showError("请输入8-16位任意内容");
            return;
        }

        if (!agreement.checked) {
            showError("请阅读并勾选！");
            return;
        }
        sendRequest("/login_up", {username, password}, "POST", (data) => success(data, "/system/mall"), (error) => errFail(error))
    }

    //发送验证码
    function handleSendSms() {
        const mobile = $("#mobile").val();


        if (!mobile) {
            showError("手机号不能为空");
            return;
        }

        if(!validatePhone(mobile)&&!validateEmail(mobile)) {
            showError("请输入正确的手机号码或邮箱地址");
            return;
        }

        let countdown = 60;
        const interval = setInterval(() => {
            if (countdown === 0) {
                clearInterval(interval);
                $("#sendSms").text("验证码").prop('disabled', false);
            } else {
                countdown--;
                $("#sendSms").text(`${countdown} 秒`);
            }
        }, 1000);

        $("#sendSms").prop('disabled', true);
        $("#sendSms").text(`验证码`);

        sendRequest("/sendSms", {mobile}, "POST", (data) => success(data, ""), (error) => errFail(error))
    }

    //手机号
    function handleMobileLogin() {
        const mobile = $("#mobile").val();
        const sms = $("#sms").val();
        const agreement = document.getElementById("is_check");

        if (!mobile) {
            showError("手机号不能为空");
            return;
        }

        if (!sms) {
            showError("验证码不能为空");
            return;
        }

        if(!validatePhone(mobile)&&!validateEmail(mobile)) {
            showError("请输入正确的手机号码或邮箱地址");
            return;
        }

        if (!validateSMS(sms)) {
            showError("请输入正确的验证码");
            return;
        }

        if (!agreement.checked) {
            showError("请阅读并勾选！");
            return;
        }
        sendRequest("/login_mobile", {mobile, sms}, "POST", (data) => success(data, "/system/mall"), (error) => errFail(error))
    }

    //修改密码
    function updatePwd() {
        const username = $("#username").val();
        const password = $("#password").val();
        const mobile = $("#mobile").val();
        const sms = $("#sms").val();
        const agreement = document.getElementById("is_check");

        if (!mobile||!username||!password||!sms) {
            showError("请完整填写表单");
            return;
        }

        if (!validatePassword(password)) {
            showError("请输入8-16位任意内容");
            return;
        }

        if(!validatePhone(mobile)&&!validateEmail(mobile)) {
            showError("请输入正确的手机号码或邮箱地址");
            return;
        }

        if (!agreement.checked) {
            showError("请阅读并勾选！");
            return;
        }

        sendRequest("/update/pwd", {username,password,mobile,sms}, "POST", (data) => success(data, ""), (error) => errFail(error))
    }


    // 关闭弹出窗口
    document.getElementById("closeButton").addEventListener("click", closeError);
    document.getElementById("closeButton01").addEventListener("click", closeError);

    // 初始化内容
    updateContent(defaultContent);
}

$(document).ready(initContent);

// 发送 AJAX 请求
function sendRequest(url, data, method, successCallback, errorCallback) {
    let allCookies = document.cookie; // 从 localStorage 获取 token

    const headers = {
        "Content-Type": "application/json",
    };
    // 如果 token 和 userId 存在，添加到请求头
    if (allCookies) {
        headers["Cookie"] = allCookies;
    }
    $.ajax({
        url: url,
        data: JSON.stringify(data),
        type: method,
        headers: headers, // 设置自定义请求头
        success: successCallback,
        error: errorCallback,
    });
}

//成功请求
function success(data, url) {
    if ((data.code === 1 && data.message === "success")||(data.code === 1 && data.message !== "success")){
        if (url !== "") {
            localStorage.setItem("user",data.data.userdata)
            location.href = url
            return
        }
        showError(data.message);
    } else if (data.code !== 1 && data.message !== "success") {
        showError(data.message);
    }
}

//失败请求
function errFail(error) {
    showError(error.message || "请求失败");
}